import { Button, Divider, MenuButton } from '@alifd/next';
import { t } from '@lingui/macro';
import React from 'react';

type DropDownItem = {
  title: string;
  show?: boolean;
  onClick?: void | any;
  color?: string;
}

interface MoreFuncDropDownProps {
  dropdownItems: Array<DropDownItem>;
  maxShow?: number;
}

type showItem = {
  text: Array<DropDownItem>;
  menu: Array<DropDownItem>;
  index: number;
}

const MoreFuncDropDown = (props: MoreFuncDropDownProps) => {
  const { dropdownItems = [], maxShow = 2 } = props;
  const showItems = dropdownItems.filter(({ show = true }) => (show));
  const len = showItems.length;

  const items = showItems.reduce((res: showItem, cur: DropDownItem) => {
    const { index } = res;
    if (index < maxShow) {
      res.text.push(cur);
    } else {
      res.menu.push(cur);
    }
    res.index++;
    return res;
  }, {
    text: [],
    menu: [],
    index: 0,
  });

  if (len <= 0) return <></>;

  return (
    <>
      {items.text.length > 0 && (
        <>
          {items.text.map((itemInfo, idx) => {
            const { title, onClick, color } = itemInfo;
            return (
              <React.Fragment key={title}>
                {idx !== 0 && <Divider direction="ver" />}
                <Button
                  type="primary"
                  style={{ color }}
                  text
                  onClick={onClick}
                >
                  {t`${title}`}
                </Button>
              </React.Fragment>
            );
          })}
        </>
      )}

      {items.menu.length > 0 && (
        <>
          <Divider direction="ver" />
          <MenuButton text type="primary" label="更多">
            {items.menu.map((itemInfo, idx) => {
              const { title, onClick, color } = itemInfo;
              return (
                <MenuButton.Item
                  key={`${title}${idx}`}
                  style={{ color }}
                  onClick={onClick}
                >
                  {title}
                </MenuButton.Item>
              );
            })}
          </MenuButton>
        </>
      )}
    </>
  );
};

export default MoreFuncDropDown;
